/**
 * Created by MingIr on 2017/1/22.
 * @author:bjzhang
 */

/**
 * Created by MingIr on 2017/1/18.
 * @author:bjzhang
 */

import React,{ Component } from 'react';
import {
    View,
    StyleSheet,
    Text,
    Image,
    Dimensions,
    ListView,
    TouchableOpacity,
    findNodeHandle,
    RefreshControl,
    ActivityIndicator, Alert
} from 'react-native';

import PHead from '../module/header';
import renderIf from '../module/renderIf';
import PFooter from '../module/footer';
import NewChest from  '../chest/new-chest';
import { common } from '../module/common'
import Toast from "react-native-root-toast";

const WINDOW_DIMENSIONS = Dimensions.get('window');
const SPECIAL_CHEST_IMG = [
    require('../../icon/btn/btn_money.png'),
    require('../../icon/btn/btn_shopping.png'),
];
const CHEST_CONTENT_TITLE = [
    '留下了一张照片！',
    '留下了一段视频！',
    '留下了一个大红包！',
    '留下了一个特别的礼物！',
]

export default class MineChests extends Component{
    constructor(props){
        super(props);
        let dataSource = new ListView.DataSource({ rowHasChanged:(r1,r2) => r1 !== r2 });
        this.state = {
            dataSource,
            viewNew:false,
            type:1,   // 1-发送的，2-收到的，3-被人点赞的
            isRefreshing:false,
            notData:false,
            isAnimating:true,
            bagCount:{sendCount:0,receiveCount:0,likeCount:0}
        };
        this.take = 10;
        // this.isAnimating = true;
        this.skip = [0,0,0];
        this.isFirstTime = true;
        this.sourceData = {'1':[],'2':[],'3':[]};
        this.route = {'1':'ImageDetail','2': 'VideoDetail','3':'RedPacketDetail','4':'EventDetail'};
        if(typeof userInfo != 'undefined' && userInfo && Object.keys(userInfo).length != 0){
            this.headerImage = { uri:userInfo.avatar };
        }
    }
    componentDidMount(){
        this.getBagCount();
        this._genRows({type:this.state.type});
    }
    componentWillMount(){
    }
    newChest(){
        // alert('New Chest');
        this.setState({viewNew:true});
    }
    rightClick(){
        this.props.navigation.navigate('Login');
    }
    closeNew(){
        this.setState({viewNew:false});
    }
    getBags(type){
        this.setState({type:type});
        this.isFirstTime = true;
        if(!this.skip[type-1]) {
            this.setState({isAnimating:true,notData:false});
            this._genRows({type: type});
        }else{
            this.setState({ dataSource:this.state.dataSource.cloneWithRows(this.sourceData[type]) });
        }
    }
    onRefresh(){
        let that = this;
        this.setState({isRefreshing: true});
    }
    onLoading(){
        if(this.isFirstTime) {
            this.isFirstTime = false;
            return;
        }
        if(!this.state.isAnimating && !this.state.notData){
            this.setState({isAnimating:true});
            // this.isAnimating = true;
            this._genRows({type:this.state.type});
        }
    }
    getBagCount(){
        let that = this;
        common.get(common.api.user.bagcount).then(res => {
            that.setState({ bagCount:res });
        }).catch(err => {
            common.loginLose(that.props.navigation,err['statusCode']);
        });
    }
    onBagDetail(bag:{ id:number,type:number }){
        let that = this;
        common.get(common.api.user.bagdetail,{id:bag.id,type:bag.type}).then(res => {
            that.props.navigation.navigate(that.route[bag.type],{ bag: res });
        }).catch(err => {
            var statusCode = err['statusCode'];
            if(statusCode == 1005){
                that.props.navigation.navigate('Login');
                return;
            }else if(statusCode == 1006){
                Alert.alert('账号在其他设备登陆',[{text:'确定',onPress:() => {
                    that.props.navigation.navigate('Login');
                }}]);
                return;
            }
        });
    }
    render(){
        return(
            <View style={{flex:1}}>
                <View style={styles.container}>
                    <PHead navigation={ this.props.navigation } title='我的' onRightEvent={this.rightClick.bind(this)} rightText="设置"></PHead>
                    <ListView dataSource={this.state.dataSource}
                              renderRow={this._renderRow.bind(this)}
                              renderHeader={this._renderHeader.bind(this)}
                              renderFooter={this._renderFooter.bind(this)}
                              scrollEnabled={true}
                              onEndReachedThreshold={10}
                              onEndReached={this.onLoading.bind(this)}
                              style={styles.table}/>
                    <PFooter onMessage={ ()=> this.props.navigation.navigate('MineConversations') }
                             onFindChest={ ()=> this.props.navigation.navigate('Chest') }
                             onNewChest={this.newChest.bind(this)} />
                </View>
                {renderIf(this.state.viewNew)(
                    <View style={[styles.blurView,styles.container,{backgroundColor:'rgba(0,0,0,.5)'}]}>
                        <NewChest onNavigation={this.props.navigation} onClosed={this.closeNew.bind(this)}/>
                    </View>
                )}
            </View>
        );
    }
    _renderHeader(){
        return(
            <View style={[styles.container,styles.flexStart]}>
                <View style={styles.coverImage}>
                    <Image resizeMode={Image.resizeMode.cover}
                           style={styles.coverImage}
                           source={this.headerImage}/>
                </View>
                <View style={styles.tabControl}>
                    <View style={[styles.tabControlColumn]}>
                        <TouchableOpacity activeOpacity={.7} onPress={() => {this.getBags(1);}}>
                            <View style={[styles.tabControlTx,this.state.type == 1 ? styles.tabItemSelected: {}]}>
                                <Text style={styles.tabItemCountTx}>{this.state.bagCount.sendCount}</Text>
                                <Text style={styles.tabItemTitleTx}>发出</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.tabControlColumn}>
                        <TouchableOpacity activeOpacity={.7} onPress={() => {this.getBags(2);}}>
                            <View style={[styles.tabControlTx,this.state.type == 2 ? styles.tabItemSelected: {}]}>
                                <Text style={styles.tabItemCountTx}>{this.state.bagCount.receiveCount}</Text>
                                <Text style={styles.tabItemTitleTx}>获得</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={[styles.tabControlColumn]}>
                        <TouchableOpacity activeOpacity={.7} onPress={() => {this.getBags(3);}}>
                            <View style={[styles.tabControlTx,this.state.type == 3 ? styles.tabItemSelected: {}]}>
                                <Text style={styles.tabItemCountTx}>{this.state.bagCount.likeCount}</Text>
                                <Text style={styles.tabItemTitleTx}>点赞</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        );
    }
    _renderRow(rowData:{id:number,userId:number,nickName:string,sex:number,avatar:string,thumbnail:string,time:string,type:number,location:string,status:number}){
        let picH = {
            uri:rowData.avatar,
        };
        let picC = {
            uri:rowData.thumbnail
        };
        return(
            <View style={styles.row}>
                <View style={styles.columnHead}>
                    <View style={styles.columnNickName}>
                        <Image style={styles.headerImg} source={picH}></Image>
                        <Text style={styles.nickNameTx}>{rowData.nickName}</Text>
                    </View>
                    <Text style={styles.timeTx}>{rowData.time}</Text>
                </View>
                <TouchableOpacity style={styles.contentWrap} activeOpacity={.7} onPress={()=>{ this.onBagDetail({id:rowData.id, type:rowData.type}); }}>
                    {renderIf((rowData.type == 3 || rowData.type == 4))(
                        <Image source={SPECIAL_CHEST_IMG[(rowData.type - 3)]}/>
                    )}
                    {renderIf(rowData.type == 1 || rowData.type == 2)(
                        <View style={[styles.imageWrap,styles.contentImg]}>
                            <Image onPress={()=>{alert('112');}} style={styles.contentImg} source={picC}>
                                {renderIf(rowData.type == 2)(
                                    <View style={styles.coverLayout}>
                                        <Image source={require('../../icon/common/icon_play_mini.png')}/>
                                    </View>
                                )}
                            </Image>
                        </View>
                    )}
                    <Text style={styles.contentTitle}>{CHEST_CONTENT_TITLE[rowData.type - 1]}</Text>
                </TouchableOpacity>
                <View style={styles.addressWrap}>
                    <Image source={require('../../icon/common/icon_map.png')}/>
                    <Text style={styles.addressTx}>{rowData.location}</Text>
                </View>
            </View>
        );
    }
    _renderFooter() {
        if(this.state.isAnimating) {
            return (
                <ActivityIndicator animating={this.state.isAnimating} style={[styles.lodingICO]}/>
            );
        }else if(this.state.notData){
            return (
                <View style={styles.lodingICO}><Text style={{fontSize:12,color:'#C8C8C8'}}>亲，没有更多的数据了</Text></View>
            );
        }
    }
    _genRows(pressData:{type:number}):Array<string>{
        let that = this;
        var api = [common.api.user.sendbags,common.api.user.receivebags,common.api.user.likes];
        common.get(api[pressData.type - 1],{take:this.take,skip:this.skip[pressData.type-1] }).then(res => {
            that.sourceData[pressData.type] = that.sourceData[pressData.type].concat(res);
            if(that.sourceData[pressData.type] && that.sourceData[pressData.type].length > 0) {
                that.setState({
                    dataSource: that.state.dataSource.cloneWithRows(that.sourceData[pressData.type]),
                    isAnimating: false
                });
            }else{
                that.setState({
                    dataSource: new ListView.DataSource({ rowHasChanged:(r1,r2) => r1 !== r2 }),
                    isAnimating: false
                });
            }
            if(res && res.length > 0){
                that.skip[pressData.type - 1] += res.length;
            }else{
                that.setState({ notData:true });
            }
        }).catch(err => {
            if(!common.loginLose(that.props.navigation,err['statusCode'])){
                that.setState({ notData:true,isAnimating:false });
            }
        });
    }
}
// refreshControl={
// <RefreshControl
//     refreshing={this.state.isRefreshing}
//     onRefresh={this.onRefresh.bind(this)}
//     tintColor="#ff0000"
//     title="加载中..."
//     titleColor="#C8C8C8"
//     colors={['#ff0000', '#00ff00', '#0000ff']}
//     progressBackgroundColor="#B0B2C2"
// />
// }
const styles = StyleSheet.create({
    container:{
        flex:1,
        flexDirection:'column',
        backgroundColor:'#fff',
    },
    blurView: {
        position: "absolute",
        left: 0,
        top: 0,
        bottom: 0,
        right: 0,
    },
    spaceBetween:{
        justifyContent:'space-between',
    },
    flexStart:{
        justifyContent:'flex-start',
    },
    coverImage:{
        height:280,
        width:WINDOW_DIMENSIONS.width,
    },
    tabControl:{
        flexDirection:'row',
        justifyContent:'space-between',
        marginTop:10,
        marginBottom:10,
        borderBottomWidth:.5,
        borderBottomColor:'#C8C8C8'
    },
    tabControlColumn:{
        flex:1,
        alignItems:'center',
    },
    tabControlTx:{
        alignItems:'center',
    },
    tabItemSelected:{
        borderBottomWidth:1,
        borderBottomColor:'#B0B2C2',
    },
    tabItemTitleTx:{
        fontSize:12,
        color:'#B0B2C2',
    },
    tabItemCountTx:{
        fontSize:17,
        color:'#5F6484',
    },
    table:{
        marginBottom:0,
        padding:0,
    },
    row:{
        borderWidth:.4,
        borderColor:'#C8C8C8',
        marginLeft:15,
        marginRight:15,
        paddingTop:15,
        paddingRight:15,
        paddingLeft:15,
        paddingBottom:20,
        marginBottom:10,
    },
    headerImg:{
        width:29,
        height:29,
        borderRadius:29,
        backgroundColor:'transparent',
    },
    columnHead:{
        flexDirection:'row',
        justifyContent:'space-between',
        alignItems:'center',
    },
    columnNickName:{
        flexDirection:'row',
        justifyContent:'flex-start',
        alignItems:'center',
    },
    nickNameTx:{
        color:'#8C959F',
        fontSize:15,
        marginLeft:10,
    },
    timeTx:{
        color:'#8C959F',
        fontSize:12,
    },
    contentWrap:{
        paddingTop:30,
        justifyContent:'center',
        alignItems:'center',
    },
    imageWrap:{
        flex:1,
        justifyContent:'center',
        alignItems:'center',
    },
    contentTitle:{
        fontSize:12,
        color:'#5F6484',
        marginTop:10,
    },
    addressWrap:{
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center',
        marginTop:20,
    },
    addressTx:{
        fontSize:14,
        color:'#B0B2C2',
        marginLeft:10,
    },
    contentImg:{
        width:100,
        height:80,
    },
    coverLayout:{
        flex:1,
        justifyContent:'center',
        alignItems:'center',
        backgroundColor:'rgba(0,0,0,.2)',
    },
    lodingICO:{
        alignItems:'center',
        justifyContent:'center',
        padding:8,
        backgroundColor:'#fff',
        transform:[{scale:1.1}]
    }
});
